// @ts-nocheck
import React, { useEffect, useState, useImperativeHandle, forwardRef, useRef, memo } from 'react';
import { Table, Card, Tooltip, message } from 'antd';
import SearchForm from './SearchForm';
import ColumnsSetting from './ColumnsSetting';
import { isEqual, debounce } from 'lodash';
import { ReloadOutlined, QuestionCircleOutlined } from '@ant-design/icons';
import './index.less';

const getInitialValues = (columns) => {
  return columns.reduce((cur, next) => {
    const { dataIndex, initialValue } = next
    if (initialValue) {
      cur[dataIndex] = initialValue
    }
    return cur
  }, {})
}

/**
 * @name 标准列表页组件
 *
 * @description 包含 搜素表单 列表分页 工具条  这三部分生成
 *
 * ProTable 封装了分页和搜索表单的 table组件
 */

 const ProTable = forwardRef((props, actionRef) => {
  //自定义先前状态钩子
  const usePrevState = (value) => {
    const ref = useRef();
    useEffect(() => {
      ref.current = value;
    });
    return ref.current;
  };

  const [dataSource, setDataSource] = useState([]);
  const [tableColumns, setTableColumns] = useState(props.columns || []);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({ pageNum: 1, pageSize: 10 });
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  
  // 搜索表单初始值
  const initialValues = getInitialValues(props.columns)
  const [searchFormValue, setSearchFormValue] = useState({
    ...initialValues,
  });

  const prevPagination = usePrevState(pagination);
  const prevSearchFormValue = usePrevState(searchFormValue);

  const tableFormRef = useRef();

  //请求列表数据
  const fetchData = debounce(
    async () => {
      const { request, params = {} } = props;
      if (!request) return;
      setLoading(true);
      try {
        const res = await request({
          ...searchFormValue,
          ...pagination,
          ...params,
        });
        if (res) {
          setDataSource(res.data);
          setTotal(res.total);
        }
        setLoading(false);
      } catch (error) {
        console.warn(error);
        setDataSource([]);
        setLoading(false);
      }
    },
    300,
    { leading: true, trailing: false, maxWait: 300 },
  );

  useEffect(() => {
    if (!isEqual(prevPagination, pagination) || !isEqual(prevSearchFormValue, searchFormValue)) {
      fetchData();
    }
  }, [searchFormValue, pagination]);

  //设置分页
  const setPaginationMethod = (pageNum, pageSize) => {
    setPagination({ pageNum, pageSize });
  };

  //设置搜索表单数据
  const setSearchFormValues = (values) => {
    console.log('values: ', values);
    setSearchFormValue(values);
  };

  // 重置搜索表单数据
  const resetSearchFormValues = () => {
    setSearchFormValue(initialValues)
  }

  //重置表格选择
  const resetRowSelection = () => {
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };

  // eslint-disable-next-line
  const getSearchFormValue = () => {
    return {
      ...searchFormValue,
    };
  };

  const reset = () => {
    tableFormRef.current.reset();
    resetRowSelection();
  };

  // eslint-disable-next-line
  const exportFile = (fileName = '导出文件') => {
    
  };

  // eslint-disable-next-line
  const importFile = () => {
    //导入方法 待完善
    console.log('文件导入');
  };

  // 暴露方法到父组件
  useImperativeHandle(props.actionRef, () => ({
    setSearchInfo: (params) => {
      setSearchFormValue((prevState) => {
        return { ...prevState, ...params };
      });
    },
    getSearchInfo: () => (getSearchFormValue())
    ,
    // 刷新
    reload: () => {
      fetchData();
      resetRowSelection();
    },
    // 刷新并清空,页码也会重置，不包括表单
    reloadAndRest: () => {},
    // 清空选中项
    clearSelected: () => {},
    // 开始编辑
    startEditable: () => {},
    // 结束编辑
    startEditable: () => {},
  }));

  //列排序以及界面增删显示
  const handleColumnsChange = (val) => {
    const { columns } = props;
    const colArr = [];
    for (const i of columns) {
      for (const j of val) {
        if (i.dataIndex === j) {
          colArr.push(i);
        }
      }
    }
    const extraColumns = columns.filter((item) => !item.dataIndex);
    setTableColumns([...colArr, ...extraColumns]);
  };

  const {
    search = false,
    title = '',
    description = '',
    request,
    toolBarRender,
    customToolBarRender,
    beforeSearchSubmit = (v) => v,
    rowSelection,
    pagination: tablePaginationConfig,
    rowKey,
    columns,
    isRefresh = false,
    columnsSetting = false,
    ...other
  } = props;
  // 查询表单项
  const filterColumns = columns.filter((o) => o.valueType && !o.hideInSearch).map((item, idx) => ({ ...item, order: item.order || idx })).sort((a, b) => a.order - b.order);

  return (
    <div className='table-layout'>
      {
        search && <div className="filter-wrap" hidden={filterColumns.length === 0}>
        <Card bordered={false}>
          <SearchForm
            ref={tableFormRef}
            onSubmit={(values) => {
              setPaginationMethod(1, pagination.pageSize);
              resetRowSelection();
              setSearchFormValues(beforeSearchSubmit(values));
            }}
            onReset={() => {
              setPaginationMethod(1, pagination.pageSize);
              resetRowSelection();
              resetSearchFormValues();
            }}
            filterForm={filterColumns}
            searchConfig={search}
          />
        </Card>
      </div>
      }
      <Card bordered={false}>
        {toolBarRender && (
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              marginBottom: '10px',
            }}
          >
            <div className="table-title">
              {
                title && <span style={{ fontWeight: 'bold' }}>{title}</span>
              }
              {description && (
                <span className="table-title-description">
                  <Tooltip placement="right" title={description}>
                    <QuestionCircleOutlined />
                  </Tooltip>
                </span>
              )}
              {selectedRowKeys.length > 0 && (
                <>
                  <span className="table-title-selection">
                    <span>已选中</span>
                    <span className="selection-num">{selectedRowKeys.length}</span>
                    <span>项</span>
                  </span>
                </>
              )}
            </div>
            {
              <div style={{ textAlign: 'right' }} className="mb20">
                {toolBarRender({
                  selectedRowKeys,
                  selectedRows,
                  dataSource,
                })}
                {isRefresh && (
                  <Tooltip title="刷新">
                    <div className="table-operation" onClick={() => reset()}>
                      <ReloadOutlined />
                    </div>
                  </Tooltip>
                )}
                
                {columnsSetting && (
                  <Tooltip title="列设置">
                    <div className="table-operation">
                      <ColumnsSetting columns={columns.filter(item => !item.hideInTable)} columnsChange={handleColumnsChange} />
                    </div>
                  </Tooltip>
                )}
              </div>
            }
          </div>
        )}

        {customToolBarRender && (
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              marginBottom: '10px',
            }}
          >
            {customToolBarRender({
              selectedRowKeys,
              selectedRows,
              dataSource,
            })}
          </div>
        )}

        <Table
          {...other}
          size={'middle'}
          loading={loading}
          rowKey={rowKey}
          dataSource={dataSource}
          columns={tableColumns
            .filter((o) => !o.hideInTable)
            .map((o) => {
              if (!o.render) {
                if (
                  ['select', 'radio'].includes(o.valueType) &&
                  o.fieldProps &&
                  Array.isArray(o.fieldProps.options)
                ) {
                  o.render = (text) => {
                    try {
                      const target = o.fieldProps.options.find((item) => item.value === text);
                      return (target ? target.label : text) || '-';
                    } catch (e) {
                      return text || '-';
                    }
                  };
                } else {
                  o.render = (text) => (
                    <div
                      onClick={() => {
                        if (!o.isCopy) return;
                        const inputDom = document.createElement('input');
                        document.body.appendChild(inputDom);
                        inputDom.value = text;
                        inputDom.select(); // 选中
                        document.execCommand('copy', false);
                        inputDom.remove(); //移除
                        message.success('复制成功');
                      }}
                    >
                      {text || '-'}
                    </div>
                  );
                }
              }
              if (o.ellipsis) {
                o.ellipsis = false;
                const render = o.render;
                o.render = (text, record, index) => (
                  <div className="table-more-ellipsis">
                    <Tooltip placement="topLeft" title={render(text, record, index)}>
                      {render(text, record, index)}
                    </Tooltip>
                  </div>
                );
              }
              return o;
            })}
          pagination={{
            ...tablePaginationConfig,
            total,
            showSizeChanger: true,
            showQuickJumper: true,
            current: pagination.pageNum,
            pageSize: pagination.pageSize,
            showTotal: () => `共${total}条`,
            onChange: (pageNum, pageSize) => {
              setPaginationMethod(pageNum, pageSize);
            },
            onShowSizeChange: (current, pageSize) => {
              setPaginationMethod(current, pageSize);
            },
          }}
          rowSelection={
            rowSelection
              ? {
                  selectedRowKeys,
                  ...rowSelection,
                  onChange: (keys, rows) => {
                    if (rowSelection && rowSelection.onChange) {
                      rowSelection.onChange(keys, rows);
                    }
                    setSelectedRowKeys(keys);
                    setSelectedRows(rows);
                  },
                  getCheckboxProps: (record) => {
                    if (rowSelection && rowSelection.getCheckboxProps) {
                      return rowSelection.getCheckboxProps(record, {
                        selectedRowKeys,
                        selectedRows,
                        dataSource,
                      });
                    }
                    return undefined;
                  },
                }
              : undefined
          }
        />
      </Card>
    </div>
  );
});

export default memo(ProTable);
